package com.yohann.algorithm.kmp;

import java.util.Arrays;

/**
 * <p>
 * kmp算法
 * </p>
 *
 * @author Yohann
 * @since 2021/1/18 21:18
 */
public class KmpAlgorithm {
    public static void main(String[] args) {
        String str1 = "3434dsfghasdfdsadfg34sdff34dsfghasdfdsadfg34sdff34dsfghasdfdsadfg34sdffdsf3435";
        String str2 = "3435";

        long time1 = System.currentTimeMillis();
        System.out.println(kmp(str1, str2));
        long time2 = System.currentTimeMillis();
        System.out.println(time2 - time1);
    }

    //获取部分匹配值
    public static int[] kmpNext(String dest) {
        int[] next = new int[dest.length()];

        for (int i = 1, j = 0; i < next.length; i++) {
            //回溯
            while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
                j = next[j - 1];
            }
            if (dest.charAt(i) == dest.charAt(j)) {
                j++;
            }

            next[i] = j;
        }

        return next;
    }

    public static int kmp(String str1, String str2) {
        int[] next = kmpNext(str2);
        for (int i = 0, j = 0; i < str1.length(); i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
                j = next[j - 1];
            }

            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }

            if (j == str2.length()) {
                return i - j + 1;
            }
        }

        return -1;
    }
}